<script setup lang="ts">
import { Component, ref, toRef, watch } from "vue";
import { objectToYaml, yamlToObject } from "../../../utils";
import { md5 } from "js-md5";
type Prop = {
  title?: string; // 标题
  btnText?: string; // 按钮文本
  type?: any; // 按钮类型
  size?: any; // 按钮大小
  plain?: boolean; // 按钮是否为朴素按钮
  round?: boolean; // 按钮是否为圆角按钮
  circle?: boolean; // 按钮是否为圆形按钮
  value?: { [key: string]: any }; // yaml内容
  icon?: string | Component; // 图标
  edit?: boolean; // 是否可编辑
};

const props = defineProps<Prop>();
const emits = defineEmits(["update:value"]);

const makeObjHash = (obj: any): string => {
  return md5(JSON.stringify(obj ?? {}));
};

const yamlContent = toRef(objectToYaml(props.value));
const yamlHash = ref<string>(makeObjHash(props.value));

const showDialog = ref(false);

const onSave = () => {
  const newObjHash = makeObjHash(yamlToObject(yamlContent.value));
  if (newObjHash !== yamlHash.value) {
    emits("update:value", yamlToObject(yamlContent.value));
  }
  yamlHash.value = newObjHash;
  showDialog.value = false;
};

watch(
  () => props.value,
  newVal => {
    yamlContent.value = objectToYaml(newVal);
    makeObjHash(newVal);
  },
  { deep: true }
);
</script>

<template>
  <div class="yaml-dialog">
    <el-dialog
      v-model="showDialog"
      :title="title ?? 'Yaml'"
      width="80%"
      append-to-body
      destroy-on-close
      top="4vh"
    >
      <Codemirror
        v-model:value="yamlContent"
        :options="{
          mode: 'text/x-yaml',
          theme: 'dracula',
          smartIndent: true,
          indentUnit: 4,
          readOnly: edit ? false : 'nocursor'
        }"
      />

      <template #footer>
        <span v-if="edit" class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="onSave"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
    <el-button
      class="dialog-button"
      :type="type"
      :size="size"
      :plain="plain"
      :round="round"
      :circle="circle"
      :icon="icon"
      @click="showDialog = true"
    >
      <span v-if="btnText">{{ btnText }}</span>
    </el-button>
  </div>
</template>
<style lang="scss">
.yaml-dialog {
  float: left;
  position: relative;
  margin-right: -1px;
}

body .el-overlay .el-overlay-dialog .el-dialog {
  display: flex;
  flex-direction: column;
  height: calc(
    100vh - var(--el-dialog-margin-top) * 2 - var(--el-dialog-padding-primary) *
      2
  );
  .el-dialog__body {
    flex: 1;
    overflow: hidden;
    // height: 100%;
    // max-height: calc(100% - var(--el-dialog-padding-primary) * 2) !important;
  }
}
</style>
